package org.xfy.sys.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.ErrorCode;
import org.xfy.org.exception.BusinessException;
import org.xfy.sys.domain.Menu;
import org.xfy.sys.mapper.MenuMapper;
import org.xfy.sys.service.IMenuService;
import org.xfy.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> findByPid(Long id) {
        return menuMapper.findByPid(id);
    }

    @Override
    public List<Menu> findMenusByPIds(List<Long> ids) {
        return menuMapper.findMenusByIds(ids);
    }


    @Override
    @Transactional
    public void add(Menu menu) {
        super.add(menu);
    }

    @Override
    @Transactional
    public void update(Menu menu) {
        Menu one = menuMapper.findOne(menu.getId());
        if (!one.getParentId().equals(menu.getParentId())) { //不是最后一级部门
            List<Menu> menus = menuMapper.findByPid(menu.getId());
            if (menus.size() > 0) {
                throw new BusinessException(ErrorCode.Besiness_ERROR.getCode());
            }
        }
        menuMapper.update(menu);
    }


    @Override
    public List<Menu> getmenusTree() {
        List<Menu> all = menuMapper.findAll();
        return menusTree(all);
    }

    //部门树
    @Override
    public List<Menu> menusTree(List<Menu> menus) {
            List<Menu> top = new ArrayList<>();
            Map<Long, Menu> map = new HashMap<>();
            //将所有集合放到Map中，以他们的id为key
            for (Menu menu : menus) {
                map.put(menu.getId(),menu);
            }
            for (Menu menu : menus) {
                //Pid为空就代表为顶层
                if (menu.getParentId() == null) {
                    top.add(menu);
                } else {
                    //找到了他的上级
                    Menu menu1 = map.get(menu.getParentId());
                    //将自己放进去
                    menu1.getChildren().add(menu);
                }
            }
            return top;
        }
}
